﻿using System;
using System.Collections.Generic;
using System.Text;
using ShootSearch.Core;
using Lucene.Net.Documents;
using ShootSearch.FileSystem;
using Lucene.Net.Index;
using ShootSearch.Util;
using System.IO;
using log4net;
using ShootSearch.Logging;
using Lucene.Net.Analysis;
using Lucene.Net.Store;

namespace ShootSearch.Indexers
{
    public class LuceneIndexer: IIndexer
    {
        public const string INDEX_PATH = "Index";

        protected LuceneIndexerConfig config;
        protected IndexWriter writer;
        protected string contextPath;
        protected Analyzer analyzer;


        public LuceneIndexer()
        {
            config = new LuceneIndexerConfig();
        }

        #region IIndexer Members
        public ILog Logger { get; set; }

        public bool Create(params object[] args)
        {
            if (config==null || args == null || args.Length <2) return false;
            if (config.InterestedAttributes.Count == 0)
            {
                Log.Error(Logger, "Interested attributes count: 0");
                return false;
            }
            contextPath = args[0].ToString();
            string path = config.IndexPath;
            if (string.IsNullOrEmpty(path))
            {
                path = IO.FormatDirName(contextPath + INDEX_PATH);
            }
          
            DirectoryInfo dirInfo = null;
            try
            {
                dirInfo = new DirectoryInfo(path);
                Lucene.Net.Store.Directory dir = FSDirectory.Open(dirInfo);

                if(dirInfo.GetFiles().Length == 0)
                {
                    writer = new IndexWriter(dir, analyzer, IndexWriter.MaxFieldLength.UNLIMITED);
                }
                else
                {
                    writer = new IndexWriter(dir, analyzer, config.CreateIndex, IndexWriter.MaxFieldLength.UNLIMITED);
                }
                writer.SetMergeFactor(config.MergeFactor);
                if(config.MaxBufferedDocs>0)
                    writer.SetMaxBufferedDocs(config.MaxBufferedDocs);
                if(config.MaxMergeDocs>0)
                    writer.SetMaxMergeDocs(config.MaxMergeDocs);

            
                return true;
            }
            catch (Exception ex)
            {
                Log.Warn(Logger, "Delete error!", ex);
                return false;
            }              
         
        }

        public bool Add(object doc)
        {
            Document outputDoc = null;
            bool parsed = Parse(doc, out outputDoc);
            if (parsed)
            {
                writer.AddDocument(outputDoc);                
            }

            return parsed;


        }

        public void Close()
        {
            if (writer != null)
            {
                writer.Optimize();
                writer.Close();
            }
        }

        #endregion

        #region IConfigable Members

        public SpiderManConfig Config
        {
            get { return config; }
            set 
            {
                if (value is LuceneIndexerConfig)
                {
                    config = value as LuceneIndexerConfig;
                    CreateAnalyzer();
                }
            }
        }

   

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            if (writer != null) writer.Close();
        }

        #endregion

        #region CreateAnalyzer
        /// <summary>
        /// Initialize the Analyzer
        /// </summary>
        protected void CreateAnalyzer()
        {
            analyzer = config.Analyzer.GetObject() as Analyzer;
            if (analyzer == null) analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer();
        } 
        #endregion

        #region Parse
        /// <summary>
        /// Parse the input file into output format
        /// </summary>
        /// <param name="docInput">The input document</param>
        /// <param name="docOutput">The Lucene Document</param>
        /// <returns></returns>
        protected virtual bool Parse(object docInput, out Document docOutput)
        {
            docOutput = null;


            if (docInput is FileObject)
            {
                FileObjectText item = new FileObjectText((FileObject)docInput);
                docOutput = new Document();

                int valueCount = 0;
                for (int i = 0; i < config.InterestedAttributes.Count; i++)
                {
                    LuceneIndexerConfig.LuceneIndexerAttribute att = config.InterestedAttributes[i];
                    string value = att.ParseValue(item);
                    if (!att.AllowNull && value == null) return false;

                    if (value != null)
                    {
                        docOutput.Add(att.GetField(value));
                        valueCount++;
                    }

                }

                if (valueCount > 0)
                {
                    return true;
                }
                else return false;
            }
            else return false;



        } 
        #endregion
      
    }
}
